import { defineComponent, reactive, ref } from 'vue'
import { Form, Input, Button, Upload, message, Modal } from 'ant-design-vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import '@/views/index.scss'
import { register } from '@/api/sys/user'
import { useRouter } from 'vue-router'

export interface userInfo {
  nickName: string
  photoUrl: string
}

export default defineComponent({
  name: 'register',
  setup() {
    const router = useRouter()
    const ruleForm = ref<any>(null)

    const data = reactive({
      labelCol: { span: 5 },
      wrapperCol: { span: 15 }
    })

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    }

    const modelRef = reactive({
      nickName: '',
      photoUrl: '',
      previewImage: '',
      loading: false,
      previewVisible: false,
    })

    const uploadButton = (
      <div>
        {modelRef.loading ? <LoadingOutlined/> : <PlusOutlined/>}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    )

    const getBase64 = (img: any, callback: any) => {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    }

    const handleChange = (info: any) => {
      if (info.file.status === 'uploading') {
        modelRef.loading = true
        return
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (imageUrl: any) => {
          modelRef.photoUrl = imageUrl
          modelRef.loading = false
        })
      }
      if (info.file.status === 'error') {
        message.error('提交出错!')
        modelRef.loading = false
      }
    }

    const beforeUpload = (file: any) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        message.error('请上传JPG/PNG图片!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        message.error('图片必须小于2MB!')
      }
      return isJpgOrPng && isLt2M
    }

    const handleCancel = () => {
      modelRef.previewVisible = false
    }

    const handlePreview = async (file: any) => {
      if (!file.url && !file.preview) {
        getBase64(file.originFileObj, (imageUrl: any) => {
          file.preview = imageUrl
          modelRef.previewImage = file.url || file.preview
          modelRef.previewVisible = true
          modelRef.loading = false
        })
      }
    }

    // 所有验证都通过的情况走这里，相当于提交
    const onFinish = async (userInfo: userInfo) => {
      console.log(userInfo)
    }

    return () => (
      <div class='register-form'>
        <Form
          ref={ruleForm}
          name="control-ref"
          labelCol={data.labelCol}
          wrapperCol={data.wrapperCol}
          model={modelRef}
          onFinish={onFinish}
        >
          <Form.Item
            name="nickName"
            label="昵称"
            hasFeedback
          >
            <Input v-model={[modelRef.nickName, 'value']} placeholder='请输入昵称'/>
          </Form.Item>
          <Form.Item
            name="photoUrl"
            label="头像"
            hasFeedback
          >
            <Upload
              v-model={[modelRef.photoUrl, 'value']}
              listType="picture-card"
              showUploadList={false}
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onPreview={handlePreview}
              onChange={handleChange}>
              {modelRef.photoUrl ? <img width={102} height={102} src={modelRef.photoUrl} alt="avatar"/> : uploadButton}
            </Upload>
            <Modal
              visible={modelRef.previewVisible}
              footer={null}
              onCancel={handleCancel}>
              <img alt="example" style="width: 100%" src={modelRef.previewImage}/>
            </Modal>
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  }
})
